package com.afc.struts.bustle.commons.http;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import com.afc.struts.bustle.commons.Converter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonToTypeConverter<Type> implements Converter<String, Type>
{
  public JsonToTypeConverter(Class<Type> aClass)
  {
    type = aClass;
  }

  @Override
  public Type convert(String aSource)
  {
    try
    {
      String source = new String(aSource.getBytes(), "UTF-8");

      Gson gson = new GsonBuilder().setDateFormat("yyyy-mm-dd").create();

      Type value = gson.fromJson(new StringReader(source), type);

      return value;
    }
    catch (UnsupportedEncodingException anException)
    {
      anException.printStackTrace();
      return null;
    }
  }

  protected Class<Type> type;
}
